package week2.Chapter3.Chapter4;

public class LinkedStack<T> implements StackADT<T>{
    private int count;
    private LinearNode<T> top;
    LinearNode node = new LinearNode();
    public LinkedStack(){
        count=0;
        top=null;
    }

    /**
     * Adds the specified element to the top of this stack.
     * @param element element to be pushed on stack.
     */
    public void push(T element) {
        LinearNode<T> temp=new LinearNode<T>(element);

        temp.setNext(top);
        top = temp;
        count++;
    }

    /**
     * Removes the element at the top of this stack and returns a
     * reference to it. Throws an EmptyCollectionException if the stack
     * is empty.
     * @return T element from top of stack
     * @throws EmptyCollectionException on pop from empty stack.
     */
    public T pop() throws EmptyCollectionException {
        if (isEmpty()) {
            throw new EmptyCollectionException("Stack");
        }
        T result = top.getElements();
        top = top.getNext();
        count--;

        return result;
    }

    public T peek() {
        if (isEmpty()) {
            throw new EmptyCollectionException("Stack");
        }
        T result = top.getElements();
        top = top.getNext();
        return result;
    }


    public boolean isEmpty() {
        if(count==0) {
            return true;
        } else {
            return false;
        }
    }
    public int size() {
        return count;
    }
    public void clear(){
        top = null;
        count = 0;
    }

    @Override
    public String toString(){
        String result = "";
        node = top;
        if(node==null){
            return "";
        }
        else {
            for (int i = 0 ; i < count; i++)
            {
                result += node.getElements() + " ";
                node = node.getNext();
            }
            return result;
        }
    }
}
